<template>
  <div class="tc-con">
    <div class="zoom flex">
      <img
        src="@/assets/img/IC/small.svg"
        @click="handleZoom('small')"
        title="缩小"
      />
      <img
        src="@/assets/img/IC/100.svg"
        @click="handleZoom('100')"
        title="100%"
      />
      <img
        src="@/assets/img/IC/big.svg"
        @click="handleZoom('big')"
        title="放大"
      />
      <!-- <img src="@/assets/img/IC/screen.svg" @click="fullScreen" title="全屏" /> -->
      <img
        src="@/assets/img/IC/image.svg"
        @click="downloadImage"
        title="另存为图片"
      />
    </div>
    <div class="legend-box">
      <div class="legend-item">
        <i></i>
        <span></span>
      </div>
    </div>
    <div id="tc-chain" class="tc-chain"></div>
  </div>
</template>
<script>
import G6 from "@antv/g6";
import insertCss from "insert-css";
import { nextTick } from 'vue';
const { Util } = G6;
export default {
  props: {
    tabLabel: {
      type: String,
      default: "",
    },
    status: {
      type: Boolean,
    },
  },
  watch: {
    tabLabel(newVal) {
      this.getData();
    },
    status(newVal) {
      this.handleStatus();
    },
  },
  data() {
    return {
      tree: null,
      curList: [
        "已开展-前瞻性研究",
        "已开展-示范验证",
        "已开展-应用研发",
        "已开展-商业化推广",
        "未开展",
        "不涉及",
      ],
      colorList: [
        // "rgba(236, 113, 37,1)",
        "#EC7125",
        "#EC7125",
        "#EC7125",
        "#EC7125",
        "#0092f6",
        "#0092f6",
        // "#00d4c7",
        // "rgba(0,213,245,1)",
        // "rgba(0,213,245,1)",
        // "rgba(0,213,245,1)",
        // "#8AA99C",
        // "#8AA99C",
        // "#8AA99C",
        // "#8AA99C",
        // "#E08E41",
        // "#E08E41",

        // "red",
        // "green",
        // "blue",
        // "gray",
        // "purple",
        // "orange",
        // "rgba(19, 33, 92, 0.65)",
        // "rgba(19, 33, 92, 0.65)",
        // "rgba(19, 33, 92, 0.65)",
        // "rgba(19, 33, 92, 0.65)",
        // "rgba(19, 33, 92, 0.65)",
        // "rgba(19, 33, 92, 0.65)",
        // "#FFE9CC",
        // "#FFD399",
        // "#FFBE66",
        // "#ff9300",
        // "#0ebeff",
        // "#0ebeff",
      ],
      bgColorList: [
        // "#F4D500",
        // "#FF9A2C",
        // "#FF1B27",
        "#cb8ee8",
        "#FF9A2C",
        "#11b9af",
        "#ff6347",
        "#6495ed",
        "#26cd26"
      ],
      strokeColorList: [
        // "#F4D500",
        // "#FF9A2C",
        // "#FF1B27",
        "#c377e8",
        "#f28611",
        "#059f95",
        "#db472c",
        "#3874df",
        "#16b516"
      ],
      // 线颜色
      edgeColorList: [
        // "#000025",
        "#101010",
        // "DimGray",
        // "gray",
        "DarkGray",
        "Silver",
        "#000025",
      ]
    };
  },
  created() {},
  mounted() {
    this.getData();
    // this.chainInit();
  },
  methods: {
    getData() {
      if (this.tree) {
        this.tree.destroy(); //这个是重点
        this.tree = null;
      }
      this.$post(this.$Url.chain.queryChain, {
        chainName: this.tabLabel,
        chainType: "JSL",
        size: 10,
      }).then((res) => {
        const data = res.data;
        if (data.node.length == 0) {
          this.$emit("showOrHideNode", {
            type: "tech",
            status: false,
          });
          return;
        } else {
          this.$emit("showOrHideNode", {
            type: "tech",
            status: true,
          });
        }
        const nodeInfo = {};
        data.node.forEach((node, index) => {
          let attr = node.attributes,
            color = "#0092f6";
          attr.forEach((tr) => {
            if (tr.name == "集团现状" && tr.value) {
              let idx = this.curList.indexOf(tr.value.trim());
              if (idx > -1) {
                color = this.colorList[idx];
                // color = "#EC7125"
              }
            }
          });
            // console.log(888, color)
          nodeInfo[node.eid] = {
            label: node.name.trim(),
            alias: node.alias, // 别名
            attributes: node.attributes,
            id: node.eid,
            eid: node.eid,
            bgColor: color,
            strokeColor: color,
            parentId: "",
          };
        });
        data.link.forEach((link) => {
          // console.log(nodeInfo[link.o_eid],link);
          nodeInfo[link.o_eid].parentId = link.s_eid;
        });
        // console.log(nodeInfo, Object.values(nodeInfo));
        const resData = this.listToTree(Object.values(nodeInfo));
        // console.log("resData", resData);
        function setDirection(arr, direction) {
          arr.children?.forEach((list) => {
            list.direction = direction
            if (list.children) {
              setDirection(list, direction)
            }
          });
        }
        let len = resData.length - 1;
        resData[len].children.forEach((list, idx) => {
          list.direction = idx % 2 == 0 ? "left" : "right";
          setDirection(list, list.direction)
        });
        // console.log(111, resData[len])
        this.chainInit(resData[len]);
      });
    },
    listToTree(data) {
      // * 先生成parent建立父子关系
      const obj = {};
      data.forEach((item) => {
        obj[item.id] = item;
      });
      // * obj -> {1001: {id: 1001, parentId: 0, name: 'AA'}, 1002: {...}}
      // console.log(obj, "obj")
      const parentList = [];
      data.forEach((item) => {
        const parent = obj[item.parentId];
        if (parent) {
          // * 当前项有父节点
          parent.children = parent.children || [];
          parent.children.push(item);
        } else {
          // * 当前项没有父节点 -> 顶层
          parentList.push(item);
        }
      });
      return parentList;
    },
    chainInit(rawData) {
      
      // 根节点
      G6.registerNode(
        "dice-mind-map-root",
        {
          jsx: (cfg) => {
            // console.log("cfg", cfg);
            let width = Util.getTextSize(cfg.label, 20)[0] + 30;
            width = width > 80 ? width : 80;
            // if (cfg.label.length <= 4) {
            //   width = 60
            // } else {
            //   width = width > 84 ? width : 84;
            // }
            // width = 84
            // console.log(width, cfg.label);
            const fill = cfg.style.fill || "#53A1D9";
            const textColor = cfg.style.textColor || "#fff" || "#CBD8DD";
            // console.log(444, fill)
            // console.log(cfg.label, cfg.style);
            return `
              <group>
                <rect name="r-box" draggable="true" style={{width: ${width}, height:50, marginLeft:${-width/2}, radius: 6, fill:RoyalBlue, stroke:${fill}, cursor: pointer}}>
                  <text capture=false style={{ fill:${textColor},fontSize:20, cursor: pointer, marginTop: 20,textAlign: 'center',  }}>${cfg.label}</text>
                </rect>
              </group>
            `; 
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5],
            ];
          },
        },
        "single-node"
      );
      
      // 下1级节点
      G6.registerNode(
        "dice-mind-map-level1",
        {
          jsx: (cfg) => {
            // console.log("cfg", cfg);
            let label = cfg.label
            if (label.length > 11) {
              label = label.substring(0, 10) + "..."
            }
            let width = Util.getTextSize(cfg.label, 18)[0] + 20;
            width = width > 80 ? width : 80;
            // if (cfg.label.length <= 4) {
            //   width = 60
            // } else {
            //   width = width > 84 ? width : 84;
            // }
            // width = 84
            // console.log(width, cfg.label);
            const fill = cfg.style.fill || "#53A1D9";
            const strokeColor = cfg.style.strokeColor || "#53A1D9";
            const textColor = cfg.style.textColor || "#fff";
            // console.log(444, fill)
            // console.log(cfg.label, cfg.style);
            // console.log(999, cfg)
            return `
              <group>
                ${cfg.direction == "left" ? 
                `
                  <rect name="r-box" style={{width: ${width},height:40, radius: 6, fill:${fill}, stroke:${strokeColor}, marginLeft:${-width},cursor: pointer}} keyShape>
                    <text name="t-box" style={{ width: ${width}, fill:${textColor},fontSize:18, cursor: pointer, marginTop: 14, marginLeft:${-width/2}, textAlign: 'center',  }}>${cfg.label}</text>
                    <circle name="c-1" style={{ r:7, fill:#bae637, cursor: pointer, marginTop: 3.5, marginLeft:10}}>
                      ${cfg.collapsed ? `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: 10,textAlign: 'center',fontWeight:'bold'  }}>+</text> ` : 
                      `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: 10,textAlign: 'center',fontWeight:'bold'  }}>-</text> `}
                    </circle>
                  <rect/>
                ` : 
                `
                  <rect name="r-box" style={{width: ${width},height:40, radius: 6, fill:${fill}, stroke:${strokeColor}, cursor: pointer}} keyShape>
                    <text name="t-box" style={{ width: ${width}, fill:${textColor}, fontSize:18, cursor: pointer, marginTop: 14, marginLeft:${width/2}, textAlign: 'center',  }}>${cfg.label}</text>
                    <circle name="c-1" style={{ r:7, fill:#bae637, cursor: pointer, marginTop: 3.5, marginLeft: ${width+10}}}>
                      ${cfg.collapsed ? `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: ${width+10},textAlign: 'center',fontWeight:'bold'  }}>+</text> ` : 
                      `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: ${width+10},textAlign: 'center',fontWeight:'bold'  }}>-</text> `}
                    </circle>
                  <rect/>
                `}
                
              </group>
            `; 
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5],
            ];
          },
        },
        "single-node"
      );

      // 下2级节点
      G6.registerNode(
        "dice-mind-map-level2",
        {
          jsx: (cfg) => {
            // console.log("cfg", cfg);
            let label = cfg.label
            if (label.length > 11) {
              label = label.substring(0, 10) + "..."
            }
            let width = Util.getTextSize(label, 14)[0] + 14;
            width = width > 80 ? width : 80;
            // if (cfg.label.length <= 4) {
            //   width = 60
            // } else {
            //   width = width > 84 ? width : 84;
            // }
            // width = 84
            // console.log(width, cfg.label);
            const fill = cfg.style.fill || "#53A1D9";
            const strokeColor = cfg.style.strokeColor || "#53A1D9";
            const textColor = cfg.style.textColor || "#fff";
            // console.log(444, fill)
            // console.log(cfg.label, cfg.style);
            // console.log(999, cfg)
            return `
              <group>
                ${cfg.direction == "left" ? 
                `
                  <rect name="r-box" style={{width: ${width},height:30, radius: 4, fill:${fill}, stroke:${strokeColor}, marginLeft:${-width},cursor: pointer}} keyShape>
                    <text name="t-box" style={{ width: ${width}, fill:${textColor},fontSize:14, cursor: pointer, marginTop: 7, marginLeft:${-width/2}, textAlign: 'center',  }}>${label}</text>
                    <circle name="c-1" style={{ r:7, fill:#bae637, cursor: pointer, marginTop: -1.5, marginLeft:10}}>
                      ${cfg.collapsed ? `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: 10,textAlign: 'center',fontWeight:'bold'  }}>+</text> ` : 
                      `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: 10,textAlign: 'center',fontWeight:'bold'  }}>-</text> `}
                    </circle>
                  <rect/>
                ` : 
                `
                  <rect name="r-box" style={{width: ${width},height:30, radius: 4, fill:${fill}, stroke:${strokeColor}, cursor: pointer}} keyShape>
                    <text name="t-box" style={{ width: ${width}, fill:${textColor}, fontSize:14, cursor: pointer, marginTop: 7, marginLeft:${width/2}, textAlign: 'center',  }}>${cfg.label}</text>
                    <circle name="c-1" style={{ r:7, fill:#bae637, cursor: pointer, marginTop: -2.5, marginLeft: ${width+10}}}>
                      ${cfg.collapsed ? `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: ${width+10},textAlign: 'center',fontWeight:'bold'  }}>+</text> ` : 
                      `<text capture=false style={{ fill:#fff, cursor: pointer, marginTop: -9.5,marginLeft: ${width+10},textAlign: 'center',fontWeight:'bold'  }}>-</text> `}
                    </circle>
                  <rect/>
                `}
                
              </group>
            `; 
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5],
            ];
          },
        },
        "single-node"
      );
      
      // 叶子节点
      G6.registerNode(
        "dice-mind-map-leaf",
        {
          jsx: (cfg) => {
            // console.log("cfg", cfg);
            let width = Util.getTextSize(cfg.label, 14)[0] + 14;
            // console.log(999, cfg.label, width)
            // width = width > 80 ? width : 80;
            const fill = cfg.style.fill || "#53A1D9";
            const opacity = cfg.style.opacity || 1;
            const textColor = cfg.style.textColor || "#fff";
            const strokeColor = cfg.style.strokeColor || "#fff"
            return `
              <group>
                ${cfg.direction == "left" ? 
                `
                  <rect name="r1" style={{width: ${width},height:30, radius: 4, fill:${fill}, stroke:${strokeColor},  marginLeft:${-width}, opacity:${opacity},cursor: pointer}} keyShape>
                    <text style={{ width: ${width}, fill:${textColor}, fontSize:14, cursor: pointer, marginTop: 7, marginLeft:${-width/2}, textAlign: 'center',  }}>${cfg.label}</text>
                  <rect/>
                ` : 
                `
                  <rect name="r1" style={{width: ${width},height:30, radius: 4, fill:${fill}, stroke:${strokeColor}, fontSize:14, opacity:${opacity},cursor: pointer}} keyShape>
                    <text style={{ width: ${width}, fill:${textColor}, fontSize:14, cursor: pointer, marginTop: 7, marginLeft:${width/2}, textAlign: 'center',  }}>${cfg.label}</text>
                  <rect/>
                `}
              </group>
            `
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5],
            ];
          },
        },
        "single-node"
      );

      const dataTransform = (data) => {
        const changeData = (d, level = 0) => {
          // console.log(d);
          const data = {
            ...d,
            collapsed: false,
            level: level
          };
          if (d.children && d.children.length > 0) {
            if (level == 0) {
              data.type = "dice-mind-map-root"
            } else if (level == 1) {
              data.type = "dice-mind-map-level1";
            } else if (level == 2) {
              if (data.children && data.children.length > 0) {
                data.type = "dice-mind-map-level2";
              } else {
                data.type = "dice-mind-map-leaf";
              }
            } else {
              data.type = "dice-mind-map-leaf";
            }
          } else {
            data.type = "dice-mind-map-leaf"
          }
          // if (level < 2) {
          //   if (level == 0) {
          //     data.style = {
          //       fill: "#375F8A",
          //     };
          //     data.styleOrigin = data.style;
          //   }
          // } else {
          //   // data.type = "dice-mind-map-leaf";
          // }
          data.style = {
            fill: d.bgColor,
            strokeColor: d.strokeColor
          };
          // data.styleOrigin = data.style;

          // if (data.active) {
          //   data.style = {
          //     fill: "#3071FE",
          //   };
          //   data.styleOrigin = data.style;
          //   data.type = "dice-mind-map-root";
          // }

          // data.hover = false;
          // data.color = "#dfdfdf";
          // data.textFill = "#333333";
          if (d.children) {
            data.children = d.children.map((child) =>
              changeData(child, level + 1)
            );
          }
          return data;
        };
        return changeData(data);
      };

      insertCss(`
        .g6-component-tooltip {
          max-width: 500px;
          background-color: #ffffff;
          z-index: 10;
          // padding: 0px 10px 24px 10px;
          // box-shadow: rgb(174, 174, 174) 0px 0px 10px;
        }
        .g6-component-tooltip .tip {
          color: #999;
        }
        .g6-component-tooltip .con {
          // margin: 10px 0 20px 0;
          margin: 10px 0 0px 0;
          line-height: 25px;
        }
        .g6-component-contextmenu {
          position: relative;
          padding: 5px 0;
          background-color: #fff;
        }
        .g6-component-contextmenu .flex {
          display: flex;
        }
        .g6-component-contextmenu p {
          font-weight: bold;
          padding:5px 0 5px 10px;
        }
        .g6-component-contextmenu .rb {
          border-left: 1px solid #dfdfdf;
        }
        .g6-component-contextmenu ul {
          margin: 0;
          padding: 0;
          text-align: left;
        }
        .g6-component-contextmenu ul li {
          padding: 6px 20px;
          cursor: pointer;
        }
        .g6-component-contextmenu ul li:hover {
          background-color: #EEEEEE;
        }
      `);

      const contextMenu = new G6.Menu({
        getContent(evt) {
          return `<div class="flex">
                    <div>
                      <p>相关数据：</p>
                      <ul>
                        <li type="first">相关专利</li>
                        <li type="second">相关机构</li>
                        <li type="three">相关专家</li>
                        <li type="four">相关资讯</li>
                      </ul>
                    </div>
                    <div class="rb">
                      <p>技术分析：</p>
                      <ul>
                        <li type="patent">专利分析</li>
                        <li type="paper">论文分析</li>
                        <li type="jsztqsfx">技术主题趋势分析</li>
                        <li type="jsqylyjcfx">前沿交叉领域分析</li>
                        <li type="jscsdfx">技术成熟度分析</li>
                      </ul>
                  </div>
                  </div>`;
        },
        handleMenuClick: (target, item) => {
          const model = item.getModel();
          // console.log(target.type, model);
          let rm = ["first", "second", "three", "four"];
          if (rm.indexOf(target.type) > -1) {
            this.$emit("rightClick", model, "tech", target.type);
          } else {
            let routerInfo = {};
            // 打开C项目新页面
            if (target.type == "patent") {
              routerInfo = {
                path: "/analysis",
                query: {
                  type: "patent",
                },
              };
            } else if (target.type == "paper") {
              routerInfo = {
                path: "/analysis",
                query: {
                  type: "paper",
                },
              };
            } else if (target.type == "jsztqsfx") {
              routerInfo = {
                path: "/TecAnalysis/technologyTopicTrends",
                query: {},
              };
            } else if (target.type == "jsqylyjcfx") {
              routerInfo = {
                path: "/TecAnalysis/technologyFrontier",
                query: {},
              };
            } else if (target.type == "jscsdfx") {
              routerInfo = {
                path: "/TecAnalysis/technologyMaturity",
                query: {},
              };
            }
            const queryToStr = (info = {}) => {
              let infoStr = "";
              for (let i in info) {
                infoStr += `${i}=${info[i]}&`;
              }
              return infoStr;
            };
            const preOrder = (list) => {
              return list.reduce((res, node) => {
                res.push(node.label);
                if (node.children) res = res.concat(preOrder(node.children));
                return res;
              }, []);
            };
            let sq = "";
            // 有节点检索式则直接用节点检索式搜索
            model.attributes.forEach((attr) => {
              if (attr.name == "节点检索式" && attr.value != "") {
                sq = attr.value;
              }
            });
            if (sq) {
              routerInfo.query.sq = sq;
              // console.log("sq", sq);
              let routerUrl = `${window.globalUrl.url}#${
                routerInfo.path
              }?${queryToStr(routerInfo.query)}`;
              window.open(routerUrl, "_blank");
              return;
            }
            // 有别名则直接用别名搜索
            let alias = model.alias // 别名
            if (alias !== "") {
              alias = alias.replace(/，/g, ",")
              let arr = alias.split(",")
              let str = `"${model.label}" OR `
              str += `"${arr.join("\" OR \"")}"`
              str = `A/(${str})`
              console.log(444, str)
              routerInfo.query.sq = str;
              let routerUrl = `${window.globalUrl.url}#${
                routerInfo.path
              }?${queryToStr(routerInfo.query)}`;
              window.open(routerUrl, "_blank");
              return;
            }
            let kwList = [];
            if (target.type == "jscsdfx") {
              kwList = preOrder([model]);
            } else {
              kwList = [model.label];
            }
            let promiseList = [];
            kwList.forEach((kw) => {
              let promise = new Promise((resolve) => {
                this.$get(this.$Url.patent.termExtend, {
                  keyword: kw,
                }).then((res) => {
                  let result = res.data || [];
                  resolve(result.join(" "));
                });
              });
              promiseList.push(promise);
            });
            Promise.all(promiseList).then((res) => {
              // console.log("res", res);
              // 检索式
              let sq = `A/("${kwList.join(" ")}" OR "${res.join(" ")}")`;
              routerInfo.query.sq = sq;
              // console.log("sq", sq);
              let routerUrl = `${window.globalUrl.url}#${
                routerInfo.path
              }?${queryToStr(routerInfo.query)}`;
              window.open(routerUrl, "_blank");
            });
          }
        },
        // offsetX and offsetY include the padding of the parent container
        // 需要加上父级容器的 padding-left 16 与自身偏移量 10
        offsetX: 0,
        // 需要加上父级容器的 padding-top 24 、画布兄弟元素高度、与自身偏移量 10
        offsetY: 0,
        // the types of items that allow the menu show up
        // 在哪些类型的元素上响应
        itemTypes: ["node"],
      });

      const tooltip = new G6.Tooltip({
        offsetX: 14,
        offsetY: 14,
        // v4.2.1 起支持配置 trigger，click 代表点击后出现 tooltip。默认为 mouseenter
        trigger: "mouseenter",
        // the types of items that allow the tooltip show up
        // 允许出现 tooltip 的 item 类型
        itemTypes: ["node"],
        // custom the tooltip's content
        // 自定义 tooltip 内容
        getContent: (e) => {
          const item = e.item;
          const model = e.item.getModel();
          // setTimeout(() => {
          //   console.log(8889)
          //   this.tree.getNodes().forEach((node) => {
          //     let getModel = node.getModel(),
          //       styleOrigin = getModel.styleOrigin;
          //     this.tree.updateItem(node, {
          //       style: styleOrigin,
          //     });
          //     // if (getModel.type == "dice-mind-map-root") {
          //     //   this.tree.updateItem(node, {
          //     //     style: styleOrigin,
          //     //   });
          //     // } else if (getModel.type == "dice-mind-map-leaf") {
          //     //   this.tree.updateItem(node, {
          //     //     textFill: "#333333",
          //     //   });
          //     // }
          //   });
          //   this.tree.updateItem(item, {
          //     style: {
          //       fill: "#2f41c8",
          //     },
          //   });
          //   // if (model.type == "dice-mind-map-root") {
          //   //   this.tree.updateItem(item, {
          //   //     style: {
          //   //       fill: "#3071FE",
          //   //     },
          //   //   });
          //   // } else if (model.type == "dice-mind-map-leaf") {
          //   //   this.tree.updateItem(item, {
          //   //     textFill: "#3071FE",
          //   //   });
          //   // }
          // }, 50);

          // this.$emit("clickNode", model, "tech");
          const attributes = model.attributes;
          const outDiv = document.createElement("div");
          outDiv.style.width = "fit-content";
          //outDiv.style.padding = '0px 0px 20px 0px';
          let html = "";
          // 靠前显示
          attributes.forEach((attr) => {
            if (attr.value.length || attr.value != "") {
              if (attr.name == "集团现状" || attr.name == "重点任务") {
                html += `<div><p class="tip">${attr.name}</p><div class="con">${attr.value}</div></div>`;
              }
            }
          });
          // 靠后显示
          attributes.forEach((attr) => {
            if (attr.value.length || attr.value != "") {
              if (
                attr.name == "技术释义" ||
                attr.name == "技术发展方向" ||
                attr.name == "技术先进性"
              ) {
                html += `<div><p class="tip">${attr.name}</p><div class="con">${attr.value}</div></div>`;
              }
            }
          });
          outDiv.innerHTML = html;
          if (html == "") {
            return `<div><p class="tip">暂无内容</p></div>`;
          } else {
            return outDiv;
          }
        },
      });

      const container = document.getElementById("tc-chain");
      const width = container.scrollWidth;
      const height = container.scrollHeight || 600;
      this.tree = new G6.TreeGraph({
        container: "tc-chain",
        width,
        height,
        // fitView: true,
        // fitViewPadding: [10, 20],
        modes: {
          default: [
            {
              type: "collapse-expand",
              trigger: "click",
              onChange: function onChange(item, collapsed) {
                const data = item.getModel();
                // data.collapsed = collapsed;
                // console.log(555, data, collapsed)
                return true;
              },
              shouldBegin: (e, self) => {
                let name = e.target.get('name')
                let model = e.item.getModel()
                if (name == "r-box" || name == "t-box") { // 点击节点时不触发collapsed
                  return false
                }
                // if (name == "c-1") {
                //   model.collapsed = true
                //   return true
                // } else {
                //   model.collapsed = false
                //   return true
                // }
                model.collapsed = !model.collapsed
                this.tree.updateItem(e.item, model)

                return true
                // console.log(77, e.target.get('name'), e.item, e.item.getModel(), self)
              }
            },
            "drag-canvas",
            "zoom-canvas"
          ], // "zoom-canvas"
        },
        plugins: [tooltip, contextMenu],
        layout: {
          type: "mindmap",
          direction: "H",
          getHeight: () => {
            return 16;
          },
          getWidth: (node) => {
            let width = 0
            if (node.level === 0) {
              // width = Util.getTextSize(node.label, 20)[0] + 30
              width = 140
            } else if (node.level === 1) {
              // width = Util.getTextSize(node.label, 18)[0] + 20;
              width = 160
            } else if (node.level === 2) {
              // width = Util.getTextSize(node.label, 12)[0] + 12;
              width = 160
            } else {
              width = 100
            }
            return width
            // return node.level === 0
            //   ? Util.getTextSize(node.label, 16)[0] + 12
            //   : Util.getTextSize(node.label, 12)[0];
          },
          getVGap: () => {
            return 10;
          },
          getHGap: () => {
            return 40;
          },
          getSide: (node) => {
            return node.data.direction;
          },
        },
        defaultEdge: {
          // type: "cubic-horizontal",
          type: "polyline",
          style: {
            lineWidth: 1.5,
          },
        },
      });

      console.log(444, dataTransform(rawData))
      let data = dataTransform(rawData)
      let _ths = this
      // 设置颜色
      function setColor(d, level, color, strokeColor) {
        if (level == 0) {
          d.children.forEach((v, i) => {
            let color = _ths.bgColorList[i%(_ths.bgColorList.length)]
            let strokeColor = _ths.strokeColorList[i%(_ths.strokeColorList.length)]
            v.style = {
              fill: color,
              strokeColor: strokeColor,
              textColor: "white"
            }
            v.styleOrigin = v.style
          })
        } else {
          if (d.children && d.children.length > 0) {
            d.children.forEach((v, i) => {
              v.style = {
                fill: color,
                strokeColor: strokeColor,
                opacity: v.strokeColor == "#EC7125" ? 0.8 : 0.2,
                // textColor: v.strokeColor == "#EC7125" ? "black" : "black",
                
                textColor: v.strokeColor == "#EC7125" ? "white"  : v.type === "dice-mind-map-leaf" ? "black" : "white",
                // strokeColor: v.strokeColor
              }
              v.styleOrigin = v.style
            })
          }
        }
        if (d.children && d.children.length > 0) {
          d.children.forEach((v, i) => {
            setColor(v, level + 1, v.style.fill, v.style.strokeColor)
          })
        }
      }
      setColor(data, 0)

      // 获取edge的source对应的数据节点对象
      function getSourceObj(arr, id) {
        if (arr.length <= 0) {
          return
        }
        for (let i=0; i<arr.length; i++) {
          if (arr[i].id === id) {
            return arr[i]
          } else {
            if (arr[i].children && arr[i].children.length > 0) {
              let obj = getSourceObj(arr[i].children, id)
              if (obj) {
                return obj
              }
            }
          }
        }
      }
      // console.log(888, getSourceObj(data.children, "50396736"))
      this.tree.data(data);
      this.tree.edge((edge)=> {
        let obj = data.id === edge.source ? data : getSourceObj(data.children, edge.source)
        if (obj) {
          return {
            type: "cubic-horizontal",
            // type: "polyline",
            // color: obj.style.fill,
            // color: this.edgeColorList[obj.level],
            color: "Silver",
            style: {
              opacity: 0.5
            }
          }
        }
        return {
          type: "cubic-horizontal",
        }
      })

      this.tree.render();
      this.tree.zoom(0.8);
      this.tree.fitCenter();


      this.tree.on("node:click", (ev) => {
        const target = ev.target;
        let name = target.get('name')
        const model = ev.item.getModel();
        console.log(99, model, name)
        this.tree.getNodes().forEach(v => {
          this.tree.updateItem(v, {
            style: v.getModel().styleOrigin
          })
        })
        if (name !== "c-1") {
          this.tree.updateItem(ev.item, {
            style: {
              ...model.style,
              opacity: 1,
              fill: "#ff7f50",
              textColor: "#fff",
              strokeColor: "#ff7f50"
            }
          })
          this.$emit("clickNode", model, "tech");
        } else {
          // let collapsed = model.collapsed
          // model.collapsed = !model.collapsed
          // this.tree.updateItem(ev.item, model)
          // this.tree.layout()
          // console.log(model.collapsed )

        }
      })

      // this.tree.on('itemcollapsed', (ev) => {
      //   console.log(123, ev.target, ev.item)
      // })

      window.addEventListener("resize", () => {
        this.tree.changeSize(container.scrollWidth, container.scrollHeight);
        // this.tree.render();
      });
    },
    handleZoom(type) {
      let index = 1;
      if (type == "small") {
        index = 0.8;
      } else if (type == "big") {
        index = 1.2;
      } else if (type == "100") {
        this.tree.render();
        return;
      }
      this.tree.zoom(index);
    },
    downloadImage() {
      this.tree.downloadFullImage(this.tabLabel, "image/png", {
        padding: [100, 100, 100, 100],
      });
    },
    fullScreen() {
      // return;
      let element = document.getElementById("tc-chain");
      if (!element) {
        return;
      }
      // 全屏查看
      if (element.requestFullScreen) {
        // HTML W3C 提议
        element.requestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        // Webkit
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      }
      // 退出全屏
      if (element.requestFullScreen) {
        document.exitFullscreen();
      } else if (element.msRequestFullScreen) {
        document.msExitFullscreen();
      } else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
      } else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
      }
    },
    handleStatus() {
      // console.log(999)
      // setTimeout(() => {
      //   this.tree?.getNodes().forEach((node) => {
      //     let getModel = node.getModel(),
      //       styleOrigin = getModel.styleOrigin;
      //     this.tree.updateItem(node, {
      //       style: styleOrigin,
      //     });
      //   });
      // }, 50);
    },
  },
  components: {},
};
</script>
<style lang="scss" scoped>
.tc-con {
  height: 600px;
  position: relative;
  .zoom {
    position: absolute;
    top: -50px;
    right: 10px;
    img {
      cursor: pointer;
      margin-right: 10px;
    }
  }
  .tc-chain {
    position: relative;
    background-color: #fff;
    overflow: hidden;
  }
}
</style>
